package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {
    @Autowired
    private StockMapper stockMapper;


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext orderContext= (CreateOrderContext)context;
        List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
        List<Long> buyProductIds = orderContext.getBuyProductIds();
        if(CollectionUtils.isEmpty(buyProductIds)){
            buyProductIds = cartProductDtoList.stream().map(CartProductDto::getProductId)
                    .distinct().collect(Collectors.toList());
        }
        buyProductIds.sort(Long::compareTo);
        // 1.锁定库存
        List<Stock> stocksList = stockMapper.findStocksForUpdate(buyProductIds);
        if(CollectionUtils.isEmpty(stocksList)){
            throw new BizException(
                    OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage()
                    );
        }
        if(stocksList.size()!=buyProductIds.size()){
            throw new BizException(
                    OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage()
                    );
        }
        // 2.获得商品id与限购数量的对应关系,以及商品id与库存数量对应关系
        Map<Long, Integer> map1 = stocksList.stream().collect(Collectors.toMap(Stock::getItemId, Stock::getRestrictCount));
        Map<Long, Long> map2 = stocksList.stream().collect(Collectors.toMap(Stock::getItemId, Stock::getStockCount));
        // 3.扣减库存
        for (CartProductDto cartProductDto : cartProductDtoList) {
            // 3.1获取购物车商品id和数量
            Long cartProductId = cartProductDto.getProductId();
            Long cartProductNum= cartProductDto.getProductNum();
            // 3.2购物车数量不能超出限购数量
            if(cartProductNum>map1.get(cartProductId)){
                throw new BizException(
                        OrderRetCode.PART_OF_PRODUCTS_OVER_RESTRICT_COUNT.getCode(),
                        OrderRetCode.PART_OF_PRODUCTS_OVER_RESTRICT_COUNT.getMessage()
                );
            }
            // 3.2购物车数量不能超出库存
            if(cartProductNum>map2.get(cartProductId)){
                throw new BizException(
                        OrderRetCode.PART_OF_PRODUCTS_OVER_STOCK_COUNT.getCode(),
                        OrderRetCode.PART_OF_PRODUCTS_OVER_STOCK_COUNT.getMessage()
                );
            }
            // 3.3扣减库存
            Stock stock = new Stock();
            stock.setItemId(cartProductId);
            stock.setLockCount(cartProductNum.intValue());
            stock.setStockCount(-cartProductNum);
            stockMapper.updateStock(stock);
        }
        return true;
    }
}